﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

using log4net;

namespace MND.Telnet
{
    class Server : IMessageSourceOrigin
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Server));
        
        public event EventHandler<NewConnectionEventArgs> NewConnection;
        private Socket server;

        public void Stop()
        {

        }

        public void Run()
        {
            log.Info("Telnet Server is starting");
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            server.Bind(new IPEndPoint(IPAddress.Any, TServer.Default.PortNumber));
            server.Listen(TServer.Default.BacklogSize);
            log.Debug("Waiting for connection...");
            server.BeginAccept(new AsyncCallback(Accept),server);
        }

        private void Accept(IAsyncResult result)
        {
            log.Debug("Accepting connection...");
            try
            {
                Socket s = (Socket)result.AsyncState;
                Connection c = new Connection(s.EndAccept(result));
                EventHandler<NewConnectionEventArgs> handler = NewConnection;
                if (handler != null)
                {
                    NewConnectionEventArgs ncea = new NewConnectionEventArgs(c);
                    handler(this, ncea);
                }
            }
            catch (Exception e)
            {
                log.Error("Error while handling new connection", e);
            }
            finally
            {
                server.BeginAccept(new AsyncCallback(Accept), server);
            }
        }
    }
}
